package com.xctech.yace.single;

import lombok.NoArgsConstructor;
import org.apache.kafka.clients.consumer.ConsumerRecord;

import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@NoArgsConstructor
public class RecivedDataManger<T> {

    //双缓存队列
    private volatile Queue<T> read = new LinkedList<>();
    private volatile Queue<T> write = new LinkedList<>();

    private static RecivedDataManger queue = new RecivedDataManger();

    private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public static RecivedDataManger getInstance(){
        return queue;
    }

    /**
     * 写
     * @param msg
     * @return
     */
    public Boolean push(T msg){
        lock.writeLock().lock();
        boolean result = write.add(msg);
        lock.writeLock().unlock();
        return result;
    }

    /**
     * 读
     * @return
     */
    public T read(){
        lock.readLock().lock();
        T poll = read.poll();
        lock.readLock().unlock();
        return poll;
    }

    /**
     * 获取读队列
     * @return
     */
    public Queue<T> getRead(){
        return read;
    }

    /**
     * 获取写队列
     * @return
     */
    public Queue<T> getWrite(){
        return write;
    }

    /**
     * 交换
     */
    public void swap(){
        lock.writeLock().lock();
        Queue<T> tmp = read;
        read = write;
        write = tmp;
        lock.writeLock().unlock();
    }

}
